import {Injectable} from '@angular/core';
import {
  HttpErrorResponse,
  HttpEvent,
  HttpHandler,
  HttpHeaders,
  HttpInterceptor,
  HttpRequest,
  HttpResponse
} from '@angular/common/http';
import {Observable, of} from 'rxjs';
import {environment} from '../../environments/environment';
import {CommonTool} from '../common/common.tool';
import {catchError, mergeMap} from 'rxjs/operators';
import {Router} from '@angular/router';
import {NzMessageService} from 'ng-zorro-antd';

@Injectable()
export class BaseHttpInterceptor implements HttpInterceptor {

  /** 超时时间 */
  public DEFAULTTIMEOUT = 5000;

  /** 最大重试次数 */
  public MAXRETRYCOUNT = 3;

  /** 防止重复点击 网络重复请求 */
  public MAXDEBOUNCETIME = 1000;


  constructor(public commonTool: CommonTool,
              private router: Router,
              private message: NzMessageService) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = this.commonTool.getCookie(environment.systemToken);
    const authReq = req.clone({
      headers: new HttpHeaders({token})
    });
    // @ts-ignore
    return next.handle(authReq).pipe(mergeMap((event: any) => {
        // 正常返回，处理具体返回参数
        if (event instanceof HttpResponse && event.status === 200) {
        }
        return of(event);
      }),
      catchError((err: HttpErrorResponse) => {
        this.message.error(err.error.message);
        if (err.status === 400 && err.error.code === 'a015') {
          this.router.navigate(['/login']);
        }
        return of(err);
      }));
  }

}
